package com.xuzm.demo.auto2;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuzm.demo.entity.UserEntity;
import com.xuzm.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;

@Component
public class Realm2 extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 角色
        HashSet<String> roleSet = new HashSet<>();
        roleSet.add("admin");
        authorizationInfo.setRoles(roleSet);

        // 权限
        HashSet<String> permissionSet = new HashSet<>();
        permissionSet.add("查看");
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1、获取主题，这里就是用户名
        String username = String.valueOf(token.getPrincipal());
        // 2、根据用户名从数据库获取其真实密码，可能是加密后的
        UserEntity userEntity = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getName, username));
        SimpleAuthenticationInfo info = null;
        if(userEntity != null){
            // 3、放入info对象，
            // 参数1：真实的主体，也可是其名称等；这里是传入真实主体，后面权限验证使用
            // 参数2：用于验证登录信息的密码是否正确，与传入信息对比
            // 参数3（可选）：密码加盐
            // 参数4：一般使用使用用户名，不与其他用户冲突即可
            info = new SimpleAuthenticationInfo(userEntity, userEntity.getPassword(), new Md5Hash("abc"), username);
        }

        return info;
    }
}
